<!DOCTYPE html>
<html lang="zh">
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
<title>MyBatis动态代理开发的理解 - 听到微笑的博客</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



    <meta name="description" content="MyBatis动态代理开发时我们开发中常用的一种形式，但是他与传统MyBatis开发有哪些区别呢？而导致这些区别的原因是什么呢？">
<meta name="keywords" content="MyBatis">
<meta property="og:type" content="article">
<meta property="og:title" content="MyBatis动态代理开发的理解">
<meta property="og:url" content="http://www.tianjindong.cn/article/30374.html">
<meta property="og:site_name" content="听到微笑的博客">
<meta property="og:description" content="MyBatis动态代理开发时我们开发中常用的一种形式，但是他与传统MyBatis开发有哪些区别呢？而导致这些区别的原因是什么呢？">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.tianjindong.cn/gallery/thumbnails/f3.jpg">
<meta property="og:updated_time" content="2020-08-22T06:32:33.650Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MyBatis动态代理开发的理解">
<meta name="twitter:description" content="MyBatis动态代理开发时我们开发中常用的一种形式，但是他与传统MyBatis开发有哪些区别呢？而导致这些区别的原因是什么呢？">
<meta name="twitter:image" content="http://www.tianjindong.cn/gallery/thumbnails/f3.jpg">







<link rel="icon" href="/images/favicon.ico">


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.7.2/css/bulma.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:400,600|Source+Code+Pro">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.12.0/styles/atom-one-dark.css">


    
    
    
    <style>body>.footer,body>.navbar,body>.section{opacity:0}</style>
    

    
    
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lightgallery@1.6.8/dist/css/lightgallery.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/css/justifiedGallery.min.css">
    

    
    

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/outdatedbrowser@1.1.5/outdatedbrowser/outdatedbrowser.min.css">


    
    
    
    

<link rel="stylesheet" href="/css/back-to-top.css">


    
    

    
    
<script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?81f9c1489f84c7a99b0bd377c9fb5de8";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    
    

    
    
<link rel="stylesheet" href="/css/progressbar.css">
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

    
    
    

    
    
    


<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/iconfont.css">
</head>
<body class="is-2-column">
    <nav class="navbar navbar-main">
    <div class="container">
        <div class="navbar-brand is-flex-center">
            <a class="navbar-item navbar-logo" href="/">
            
                <img src="/images/logo.png" alt="MyBatis动态代理开发的理解" height="28">
            
            </a>
        </div>
        <div class="navbar-menu">
            
            <div class="navbar-start">
                
                <a class="navbar-item" href="/">主页</a>
                
                <a class="navbar-item" href="/categories">分类</a>
                
                <a class="navbar-item" href="/tags">标签</a>
                
                <a class="navbar-item" href="/archives">历史</a>
                
                <a class="navbar-item" href="/music.html">音乐</a>
                
                <a class="navbar-item" href="/about.html">关于</a>
                
            </div>
            
            <div class="navbar-end">
                
                
                <a class="navbar-item is-hidden-tablet catalogue" title="目录" href="javascript:;">
                    <i class="fas fa-list-ul"></i>
                </a>
                
                
                <a class="navbar-item search" title="搜索" href="javascript:;">
                    <i class="fas fa-search"></i>
                </a>
                
            </div>
        </div>
    </div>
</nav>
        
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-8-tablet is-9-desktop is-9-widescreen has-order-2 column-main"><div class="card">
    
    <div class="card-image">
        <span class="image is-7by1">
            <img class="thumbnail" src="/gallery/thumbnails/f3.jpg" alt="MyBatis动态代理开发的理解">
        </span>
    </div>
    
    <div class="card-content article ">
        
        <div class="level article-meta is-size-7 is-uppercase is-mobile is-overflow-x-auto">
            <div class="level-left">
                <time class="level-item has-text-grey" datetime="2019-07-28T10:08:06.000Z">2019-07-28</time>
                
                <div class="level-item">
                <a class="has-link-grey -link" href="/categories/常用框架/">常用框架</a>&nbsp;/&nbsp;<a class="has-link-grey -link" href="/categories/常用框架/MyBatis/">MyBatis</a>
                </div>
                
                
                <span class="level-item has-text-grey">
                    
                    
                    11 分钟 读完 (大约 1617 个字)
                </span>
                
                
            </div>
        </div>
        
        <h1 class="title is-size-3 is-size-4-mobile has-text-weight-normal">
            
                MyBatis动态代理开发的理解
            
        </h1>
        <div class="content">
            <p>MyBatis动态代理开发时我们开发中常用的一种形式，但是他与传统MyBatis开发有哪些区别呢？而导致这些区别的原因是什么呢？<a id="more"></a></p>
<h2 id="MyBatis非动态代理开发"><a href="#MyBatis非动态代理开发" class="headerlink" title="MyBatis非动态代理开发"></a><strong>MyBatis非动态代理开发</strong></h2><p>在日常开发中我们或许都使用动态代理的方式，但是动态代理开发并不是MyBatis最基本的开发模式：</p>
<h3 id="传统开发流程"><a href="#传统开发流程" class="headerlink" title="传统开发流程"></a><strong>传统开发流程</strong></h3><h4 id="第一步：在resource-目录下新建SqlMapConfig-xml文件："><a href="#第一步：在resource-目录下新建SqlMapConfig-xml文件：" class="headerlink" title="第一步：在resource/目录下新建SqlMapConfig.xml文件："></a>第一步：在<code>resource/</code>目录下新建SqlMapConfig.xml文件：</h4><figure class="highlight xml hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="hljs-meta">&lt;!DOCTYPE configuration</span></span><br><span class="line"><span class="hljs-meta">		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"</span></span><br><span class="line"><span class="hljs-meta">		"http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">environments</span> <span class="hljs-attr">default</span>=<span class="hljs-string">"development"</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">environment</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"development"</span>&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;<span class="hljs-name">transactionManager</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"JDBC"</span>/&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;<span class="hljs-name">dataSource</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"POOLED"</span>&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driver"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"jdbc:mysql://localhost:3306/test"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"980613"</span>/&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;/<span class="hljs-name">dataSource</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;/<span class="hljs-name">environment</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">environments</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"com/tjd/mapper/UserMapper.xml"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="第二步：在com-tjd-mapper包下创建映射文件："><a href="#第二步：在com-tjd-mapper包下创建映射文件：" class="headerlink" title="第二步：在com.tjd.mapper包下创建映射文件："></a>第二步：在<code>com.tjd.mapper</code>包下创建映射文件：</h4><figure class="highlight xml hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="hljs-meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" &gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">"com.tjd.mapper.UserMapper"</span>&gt;</span></span><br><span class="line">    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"getUserById"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.tjd.pojo.User"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"long"</span>&gt;</span></span><br><span class="line">        select * from user where uid = #&#123;id&#125;</span><br><span class="line">    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span></span><br><span class="line">    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"getUserByName"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.tjd.pojo.User"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"string"</span> &gt;</span></span><br><span class="line">        select * from user where uname = #&#123;name&#125;</span><br><span class="line">    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>走到这一步，MyBatis环境就搭建完成了，此时我们就需要开始进行数据库操作：</p>
<h4 id="第三步：使用MyBatis提供的API进行数据库操作"><a href="#第三步：使用MyBatis提供的API进行数据库操作" class="headerlink" title="第三步：使用MyBatis提供的API进行数据库操作"></a>第三步：使用MyBatis提供的API进行数据库操作</h4><figure class="highlight java hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyBatisTest</span> </span>&#123;</span><br><span class="line">    <span class="hljs-meta">@Test</span></span><br><span class="line">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        InputStream resource = Resources.getResourceAsStream(<span class="hljs-string">"SqlMapConfig.xml"</span>);</span><br><span class="line">        SqlSessionFactory sessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resource);</span><br><span class="line">        SqlSession session = sessionFactory.openSession();</span><br><span class="line">        Object o = session.selectOne(<span class="hljs-string">"com.tjd.mapper.UserMapper.getUserById"</span>,<span class="hljs-number">1L</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="理解传统开发流程"><a href="#理解传统开发流程" class="headerlink" title="理解传统开发流程"></a><strong>理解传统开发流程</strong></h3><p>​    在非动态代理开发时，并不需要写什么Mapper接口，只需要配置映射文件，然后获取的SqlSeesion对象，通过该对象的selectOne或selectList方法进行数据库查询即可，而这些方法只需要传入SQL语句的ID即可执行相应的SQL语句，然后将结果映射为实体类。（注：通常我们会在ID前面加上映射文件的namespace，但是如果ID没有重复的情况下，是可以直接通过ID调用SQL语句）。</p>
<p>​    <code>需要注意的是，不进行动态代理开发时，在SqlMapConfig文件中只能使用&lt;mapper resource&gt;或&lt;mapper url&gt;进行映射文件的加载</code>。而由于使用resource指定的映射文件位置，所以映射文件实际上放在哪都无所谓，只要resource指向映射文件即可。</p>
<p>​    通常在这种开发模式中，我们仍然会创建Dao层代码，对数据库操作进行封装，但是其本质并没有变，就是MyBatis框架将映射文件的SQL语句加载进系统，然后通过获取的SqlSession对象执行指定的SQL语句，所以<code>在这种开发模式中，映射配置文件的位置、文件名、namespace、statement_id的填写格式并没有强制要求，唯一的要求就是每一个namespace+id可以唯一定位一个SQL语句</code>。</p>
<h2 id="MyBatis动态代理开发"><a href="#MyBatis动态代理开发" class="headerlink" title="MyBatis动态代理开发"></a><strong>MyBatis动态代理开发</strong></h2><p>在传统开发中，我们需要指定映射文件配置的SQL语句的ID才能执行SQL语句：</p>
<figure class="highlight java hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">User user = (User)session.selectOne(<span class="hljs-string">"com.tjd.mapper.UserMapper.getUserById"</span>,<span class="hljs-number">1L</span>);</span><br></pre></td></tr></table></figure>

<p>诚然，这种方式能够正常工作，并且对于使用旧版本 MyBatis 的用户来说也比较熟悉。不过现在有了一种更简洁的方式 ——动态代理开发，这种开发模式不仅可以执行更清晰和类型安全的代码，而且还不用担心易错的字符串字面值以及强制类型转换。</p>
<h3 id="动态代理开发流程"><a href="#动态代理开发流程" class="headerlink" title="动态代理开发流程"></a><strong>动态代理开发流程</strong></h3><h4 id="第一步：创建Mapper接口"><a href="#第一步：创建Mapper接口" class="headerlink" title="第一步：创建Mapper接口"></a>第一步：创建Mapper接口</h4><p>但是如果想要进行动态代理开发就需要满足动态代理开发的要求了，在传统开发模式中有没有Mapper接口都无所谓，但是由于采用的是动态代理开发，所以必须要一个接口：</p>
<figure class="highlight java hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-keyword">package</span> com.tjd.mapper;</span><br><span class="line"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserMapper</span> </span>&#123;</span><br><span class="line">    <span class="hljs-function">User <span class="hljs-title">getUserById</span><span class="hljs-params">(Long id)</span></span>;</span><br><span class="line">    <span class="hljs-function">User <span class="hljs-title">getUserByName</span><span class="hljs-params">(String name)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="第二步：创建映射配置文件"><a href="#第二步：创建映射配置文件" class="headerlink" title="第二步：创建映射配置文件"></a>第二步：创建映射配置文件</h4><figure class="highlight xml hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="hljs-meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" &gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">"com.tjd.mapper.UserMapper"</span>&gt;</span></span><br><span class="line">    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"getUserById"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.tjd.pojo.User"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"long"</span>&gt;</span></span><br><span class="line">        select * from user where uid = #&#123;id&#125;</span><br><span class="line">    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span></span><br><span class="line">    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"getUserByName"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.tjd.pojo.User"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"string"</span>&gt;</span></span><br><span class="line">        select * from user where uname = #&#123;name&#125;</span><br><span class="line">    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>使用动态代理开发时，映射文件的namespace必须是Mapper接口的全限定类名，而SQL语句的ID必须与接口中的方法名一一对应</code>。但是映射文件名和映射文件的位置并没有强制要求，具体细节在后面讲解。</p>
<h4 id="第三步：配置MyBatis核心配置文件"><a href="#第三步：配置MyBatis核心配置文件" class="headerlink" title="第三步：配置MyBatis核心配置文件"></a>第三步：配置MyBatis核心配置文件</h4><figure class="highlight xml hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="hljs-meta">&lt;!DOCTYPE configuration</span></span><br><span class="line"><span class="hljs-meta">		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"</span></span><br><span class="line"><span class="hljs-meta">		"http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">settings</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"logImpl"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"STDOUT_LOGGING"</span> /&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">typeAliases</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"com.tjd.spring_mybatis_plus.pojo"</span>/&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">typeAliases</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">environments</span> <span class="hljs-attr">default</span>=<span class="hljs-string">"development"</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">environment</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"development"</span>&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;<span class="hljs-name">transactionManager</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"JDBC"</span>/&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;<span class="hljs-name">dataSource</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"POOLED"</span>&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driver"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"jdbc:mysql://localhost:3306/test"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span>/&gt;</span></span><br><span class="line">				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"980613"</span>/&gt;</span></span><br><span class="line">			<span class="hljs-tag">&lt;/<span class="hljs-name">dataSource</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;/<span class="hljs-name">environment</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">environments</span>&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span></span><br><span class="line">		<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"com/tjd/spring_mybatis_plus/mapper/UserMapper.xml"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></span><br><span class="line">		<span class="hljs-comment">&lt;!--&lt;mapper class="com.tjd.spring_mybatis_plus.mapper.UserMapper"&gt;&lt;/mapper&gt;--&gt;</span></span><br><span class="line">	<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span></span><br><span class="line"><span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在使用动态代理开发时，指定映射文件位置可以有四种模式：<code>&lt;mapper resource&gt;、&lt;mapper url&gt;、&lt;mapper class&gt;、&lt;package&gt;</code>，但是这四种配置模式对映射文件名和映射文件位置有着不同的影响，具体来说：</p>
<ul>
<li>在使用<code>&lt;mapper resource&gt;、&lt;mapper url&gt;</code>时，映射文件可以放在任意地方，映射文件名可以任意取；</li>
<li>在使用<code>&lt;mapper class&gt;</code>和<code>&lt;package&gt;</code>时，映射文件必须与Mapper接口处于相同的包中，并且映射文件名和接口名相同。</li>
</ul>
<h4 id="第四步：获取代理对象执行数据库操作"><a href="#第四步：获取代理对象执行数据库操作" class="headerlink" title="第四步：获取代理对象执行数据库操作"></a>第四步：获取代理对象执行数据库操作</h4><figure class="highlight java hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyBatisTest</span> </span>&#123;</span><br><span class="line">    <span class="hljs-meta">@Test</span></span><br><span class="line">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        InputStream resource = Resources.getResourceAsStream(<span class="hljs-string">"SqlMapConfig.xml"</span>);</span><br><span class="line">        SqlSessionFactory sessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resource);</span><br><span class="line">        SqlSession session = sessionFactory.openSession();</span><br><span class="line">        <span class="hljs-comment">//获取代理对象</span></span><br><span class="line">        UserMapper mapper = session.getMapper(UserMapper.class);</span><br><span class="line">        User userById = mapper.getUserById(<span class="hljs-number">1L</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="理解MyBatis动态代理开发"><a href="#理解MyBatis动态代理开发" class="headerlink" title="理解MyBatis动态代理开发"></a>理解MyBatis动态代理开发</h3><p>​    虽说是动态代理开发，但是实质的原理非常简单，就是MyBatis生成代理对象，在代理对象的方法中，会自动根据当前执行的方法名，然后定位到映射配置文件中配置的SQL语句。这就避免了我们使用字符串常量来调用SQL语句了，也避免了最后结果的强制类型转换。</p>
<p>​    在这种开发模式中，对映射配置文件有相应的要求：</p>
<ul>
<li>Mapper接口方法名和Mapper.xml中定义的SQL语句的ID一一对应。</li>
<li>映射配置文件的namespace与接口的全限定类名相同。</li>
<li>Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同。</li>
<li>Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同。</li>
</ul>
<p><code>但是对于映射配置文件位置和文件名的要求，取决于采用哪种模式加载配置文件(resource、url、class、package)</code>。</p>
<h2 id="Spring与MyBatis结合的动态代理开发"><a href="#Spring与MyBatis结合的动态代理开发" class="headerlink" title="Spring与MyBatis结合的动态代理开发"></a>Spring与MyBatis结合的动态代理开发</h2><p>参考博主的另一篇文章：<a href="./41666.html">MyBatis与Spring整合步骤</a></p>

        </div>
        
        <div class="level is-size-7 is-uppercase">
            <div class="level-start">
                <div class="level-item">
                    <span class="is-size-6 has-text-grey has-mr-7">#</span>
                    <a class="has-link-grey -link" href="/tags/MyBatis/">MyBatis</a>
                </div>
            </div>
        </div>
        
        
        
        
<div class="sharethis-inline-share-buttons"></div>
<script type="text/javascript" src="//platform-api.sharethis.com/js/sharethis.js#property=5d1b4ddd55a8b200110cdf62&amp;product=social-ab" async="async"></script>

        
    </div>
</div>



<div class="card">
    <div class="card-content">
        <h3 class="menu-label has-text-centered">喜欢这篇文章？打赏一下作者吧</h3>
        <div class="buttons is-centered">
            
                
<a class="button is-info donate">
    <span class="icon is-small">
        <i class="fab fa-alipay"></i>
    </span>
    <span>支付宝</span>
    <div class="qrcode"><img src="/images/alipay.jpg" alt="支付宝"></div>
</a>

                
                
<a class="button is-success donate">
    <span class="icon is-small">
        <i class="fab fa-weixin"></i>
    </span>
    <span>微信</span>
    <div class="qrcode"><img src="/images/wechat.png" alt="微信"></div>
</a>

                
        </div>
    </div>
</div>



<div class="card card-transparent">
    <div class="level post-navigation is-flex-wrap is-mobile">
        
        <div class="level-end">
            <a class="level level-item has-link-grey  article-nav-next" href="/article/41666.html">
                <i class="level-item fas fa-chevron-left"></i>
                <span class="level-item">MyBatis与Spring整合步骤</span>
            </a>
        </div>
        
        
        <div class="level-start">
            <a class="level level-item has-link-grey  article-nav-prev" href="/article/13726.html">
                <span class="level-item">MyBatis延迟加载策略</span>
                <i class="level-item fas fa-chevron-right"></i>
            </a>
        </div>
        
    </div>
</div>



<div class="card">
    <div class="card-content">
        <h3 class="title is-5 has-text-weight-normal">评论</h3>
        
<div id="comment-container"></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.4.1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1.4.1/dist/gitalk.min.js"></script>
<script>
    var gitalk = new Gitalk({
        clientID: 'a362d7e659d5da0b4c24',
        clientSecret: 'bfd2817b484ba4d45ad14e44bbf993fa353a4f2d',
        id: '69811fa090bd2a4faa399a609c9f47dc',
        repo: 'blog_comment',
        owner: 'tianjindong',
        admin: "tianjindong"
    })
    gitalk.render('comment-container')
</script>

    </div>
</div>
</div>
                




<div class="column is-4-tablet is-3-desktop is-3-widescreen  has-order-1 column-left ">
    
        
<div class="card widget">
    <div class="card-content">
        <nav class="level">
            <div class="level-item has-text-centered">
                <div>
                    
                        <img class="image is-128x128 has-mb-6" src="/images/avatar.png" alt="听到微笑">
                    
                    
                    <p class="is-size-4 is-block">
                        听到微笑
                    </p>
                    
                    
                    <p class="is-size-6 is-block">
                        Java Engineer
                    </p>
                    
                    
                    <p class="is-size-6 is-flex is-flex-center has-text-grey">
                        <i class="fas fa-map-marker-alt has-mr-7"></i>
                        <span>中国 上海</span>
                    </p>
                    
                </div>
            </div>
        </nav>
        <nav class="level is-mobile">
            <div class="level-item has-text-centered is-marginless">
                <div>
                    <p class="heading">
                        文章
                    </p>
                    <p class="title has-text-weight-normal">
                        54
                    </p>
                </div>
            </div>
            <div class="level-item has-text-centered is-marginless">
                <div>
                    <p class="heading">
                        分类
                    </p>
                    <p class="title has-text-weight-normal">
                        20
                    </p>
                </div>
            </div>
            <div class="level-item has-text-centered is-marginless">
                <div>
                    <p class="heading">
                        标签
                    </p>
                    <p class="title has-text-weight-normal">
                        30
                    </p>
                </div>
            </div>
        </nav>
        <div class="level">
            <a class="level-item button is-link is-rounded" href="https://github.com/tianjindong" target="_blank">
                关注我</a>
        </div>
        
        
        <div class="level is-mobile">
            
            <a class="level-item button is-white is-marginless" target="_blank" title="Github" href="https://github.com/tianjindong">
                
                <i class="iconfont-github icon-GitHub"></i>
                
            </a>
            
            <a class="level-item button is-white is-marginless" target="_blank" title="Gitee" href="https://gitee.com/tianjindong">
                
                <i class="iconfont-gitee icon-gitee"></i>
                
            </a>
            
            <a class="level-item button is-white is-marginless" target="_blank" title="CSDN" href="https://blog.csdn.net/tianjindong0804">
                
                <i class="iconfont-csdn icon-CN_csdnnet"></i>
                
            </a>
            
            <a class="level-item button is-white is-marginless" target="_blank" title="Twitter" href="https://twitter.com/HearingSmile">
                
                <i class="iconfont-twitter icon-twitter"></i>
                
            </a>
            
        </div>
        
    </div>
</div>
    
        
<div class="card widget" id="toc">
    <div class="card-content">
        <div class="menu">
            <h3 class="menu-label">
                目录
            </h3>
            <ul class="menu-list"><li>
        <a class="is-flex" href="#MyBatis非动态代理开发">
        <span class="has-mr-6">1</span>
        <span>MyBatis非动态代理开发</span>
        </a><ul class="menu-list"><li>
        <a class="is-flex" href="#传统开发流程">
        <span class="has-mr-6">1.1</span>
        <span>传统开发流程</span>
        </a><ul class="menu-list"><li>
        <a class="is-flex" href="#第一步：在resource-目录下新建SqlMapConfig-xml文件：">
        <span class="has-mr-6">1.1.1</span>
        <span>第一步：在resource/目录下新建SqlMapConfig.xml文件：</span>
        </a></li><li>
        <a class="is-flex" href="#第二步：在com-tjd-mapper包下创建映射文件：">
        <span class="has-mr-6">1.1.2</span>
        <span>第二步：在com.tjd.mapper包下创建映射文件：</span>
        </a></li><li>
        <a class="is-flex" href="#第三步：使用MyBatis提供的API进行数据库操作">
        <span class="has-mr-6">1.1.3</span>
        <span>第三步：使用MyBatis提供的API进行数据库操作</span>
        </a></li></ul></li><li>
        <a class="is-flex" href="#理解传统开发流程">
        <span class="has-mr-6">1.2</span>
        <span>理解传统开发流程</span>
        </a></li></ul></li><li>
        <a class="is-flex" href="#MyBatis动态代理开发">
        <span class="has-mr-6">2</span>
        <span>MyBatis动态代理开发</span>
        </a><ul class="menu-list"><li>
        <a class="is-flex" href="#动态代理开发流程">
        <span class="has-mr-6">2.1</span>
        <span>动态代理开发流程</span>
        </a><ul class="menu-list"><li>
        <a class="is-flex" href="#第一步：创建Mapper接口">
        <span class="has-mr-6">2.1.1</span>
        <span>第一步：创建Mapper接口</span>
        </a></li><li>
        <a class="is-flex" href="#第二步：创建映射配置文件">
        <span class="has-mr-6">2.1.2</span>
        <span>第二步：创建映射配置文件</span>
        </a></li><li>
        <a class="is-flex" href="#第三步：配置MyBatis核心配置文件">
        <span class="has-mr-6">2.1.3</span>
        <span>第三步：配置MyBatis核心配置文件</span>
        </a></li><li>
        <a class="is-flex" href="#第四步：获取代理对象执行数据库操作">
        <span class="has-mr-6">2.1.4</span>
        <span>第四步：获取代理对象执行数据库操作</span>
        </a></li></ul></li><li>
        <a class="is-flex" href="#理解MyBatis动态代理开发">
        <span class="has-mr-6">2.2</span>
        <span>理解MyBatis动态代理开发</span>
        </a></li></ul></li><li>
        <a class="is-flex" href="#Spring与MyBatis结合的动态代理开发">
        <span class="has-mr-6">3</span>
        <span>Spring与MyBatis结合的动态代理开发</span>
        </a></li></ul>
        </div>
    </div>
</div>

    
        
    
    
        <div class="column-right-shadow  is-sticky">
        
            
<div class="card widget">
    <div class="card-content">
        <h3 class="menu-label">
            最新文章
        </h3>
        
        <article class="media">
            
            <a href="/article/37883.html" class="media-left">
                <p class="image is-64x64">
                    <img class="thumbnail" src="http://image.bigcoder.cn/20210116215841.png" alt="DockerSwarm架构详解(转载)">
                </p>
            </a>
            
            <div class="media-content">
                <div class="content">
                    <div><time class="has-text-grey is-size-7 is-uppercase" datetime="2021-01-16T13:46:04.000Z">2021-01-16</time></div>
                    <a href="/article/37883.html" class="has-link-black-ter is-size-6">DockerSwarm架构详解(转载)</a>
                    <p class="is-size-7 is-uppercase">
                        <a class="has-link-grey -link" href="/categories/Docker/">Docker</a>
                    </p>
                </div>
            </div>
        </article>
        
        <article class="media">
            
            <a href="/article/54308.html" class="media-left">
                <p class="image is-64x64">
                    <img class="thumbnail" src="/gallery/thumbnails/h4.jpg" alt="B树和B+树与磁盘读写之间的联系">
                </p>
            </a>
            
            <div class="media-content">
                <div class="content">
                    <div><time class="has-text-grey is-size-7 is-uppercase" datetime="2019-08-24T02:20:31.000Z">2019-08-24</time></div>
                    <a href="/article/54308.html" class="has-link-black-ter is-size-6">B树和B+树与磁盘读写之间的联系</a>
                    <p class="is-size-7 is-uppercase">
                        <a class="has-link-grey -link" href="/categories/数据结构/">数据结构</a>
                    </p>
                </div>
            </div>
        </article>
        
        <article class="media">
            
            <a href="/article/21035.html" class="media-left">
                <p class="image is-64x64">
                    <img class="thumbnail" src="/gallery/thumbnails/h3.jpg" alt="什么是B+树">
                </p>
            </a>
            
            <div class="media-content">
                <div class="content">
                    <div><time class="has-text-grey is-size-7 is-uppercase" datetime="2019-08-19T10:25:05.000Z">2019-08-19</time></div>
                    <a href="/article/21035.html" class="has-link-black-ter is-size-6">什么是B+树</a>
                    <p class="is-size-7 is-uppercase">
                        <a class="has-link-grey -link" href="/categories/数据结构/">数据结构</a>
                    </p>
                </div>
            </div>
        </article>
        
        <article class="media">
            
            <a href="/article/8567.html" class="media-left">
                <p class="image is-64x64">
                    <img class="thumbnail" src="/gallery/thumbnails/f6.jpg" alt="什么是B-树">
                </p>
            </a>
            
            <div class="media-content">
                <div class="content">
                    <div><time class="has-text-grey is-size-7 is-uppercase" datetime="2019-08-19T10:24:50.000Z">2019-08-19</time></div>
                    <a href="/article/8567.html" class="has-link-black-ter is-size-6">什么是B-树</a>
                    <p class="is-size-7 is-uppercase">
                        <a class="has-link-grey -link" href="/categories/数据结构/">数据结构</a>
                    </p>
                </div>
            </div>
        </article>
        
        <article class="media">
            
            <a href="/article/62369.html" class="media-left">
                <p class="image is-64x64">
                    <img class="thumbnail" src="/gallery/thumbnails/h1.jpg" alt="什么是一致性Hash算法">
                </p>
            </a>
            
            <div class="media-content">
                <div class="content">
                    <div><time class="has-text-grey is-size-7 is-uppercase" datetime="2019-08-16T07:27:10.000Z">2019-08-16</time></div>
                    <a href="/article/62369.html" class="has-link-black-ter is-size-6">什么是一致性Hash算法</a>
                    <p class="is-size-7 is-uppercase">
                        <a class="has-link-grey -link" href="/categories/数据结构/">数据结构</a>
                    </p>
                </div>
            </div>
        </article>
        
    </div>
</div>

        
            
        
        </div>
    
</div>

                
            </div>
        </div>
    </section>
    <footer class="footer">
    <div class="container">
        <div class="level">
            <div class="level-start has-text-centered-mobile">
                <a class="footer-logo is-block has-mb-6" href="/">
                
                    <img src="/images/logo.png" alt="MyBatis动态代理开发的理解" height="28">
                
                </a>
                <p class="is-size-7">
                &copy; 2021 听到微笑&nbsp;
                Powered by <a href="https://hexo.io/" target="_blank">Hexo</a> & <a href="https://github.com/ppoffice/hexo-theme-icarus" target="_blank">Icarus</a>
                
                </p>
            </div>
            <div class="level-end">
            
            </div>
        </div>
    </div>
</footer>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/min/moment-with-locales.min.js"></script>
<script>moment.locale("zh-CN");</script>


    
    
    
    <script src="/js/animation.js"></script>
    

    
    
    
    <script src="https://cdn.jsdelivr.net/npm/lightgallery@1.6.8/dist/js/lightgallery.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js" defer></script>
    <script src="/js/gallery.js" defer></script>
    

    
    

<div id="outdated">
    <h6>Your browser is out-of-date!</h6>
    <p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update
            my browser now </a></p>
    <p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/outdatedbrowser@1.1.5/outdatedbrowser/outdatedbrowser.min.js" defer></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        outdatedBrowser({
            bgColor: '#f25648',
            color: '#ffffff',
            lowerThan: 'flex'
        });
    });
</script>


    
    
<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.5/unpacked/MathJax.js?config=TeX-MML-AM_CHTML" defer></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    MathJax.Hub.Config({
        'HTML-CSS': {
            matchFontHeight: false
        },
        SVG: {
            matchFontHeight: false
        },
        CommonHTML: {
            matchFontHeight: false
        },
        tex2jax: {
            inlineMath: [
                ['$','$'],
                ['\\(','\\)']
            ]
        }
    });
});
</script>

    
    

<a id="back-to-top" title="回到顶端" href="javascript:;">
    <i class="fas fa-chevron-up"></i>
</a>
<script src="/js/back-to-top.js" defer></script>


    
    

    
    
    
    

    
    
    
    
    
    <script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.4/dist/clipboard.min.js" defer></script>
    <script src="/js/clipboard.js" defer></script>
    

    
    
    


<script src="/js/main.js" defer></script>

    
    <div class="searchbox ins-search">
    <div class="searchbox-container ins-search-container">
        <div class="searchbox-input-wrapper">
            <input type="text" class="searchbox-input ins-search-input" placeholder="想要查找什么...">
            <span class="searchbox-close ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="searchbox-result-wrapper ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: '文章',
                PAGES: '页面',
                CATEGORIES: '分类',
                TAGS: '标签',
                UNTITLED: '(无标题)',
            },
            CONTENT_URL: '/content.json',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script src="/js/insight.js" defer></script>
<link rel="stylesheet" href="/css/search.css">
<link rel="stylesheet" href="/css/insight.css">
    
</body>
</html>